package cn.information.view.extend;

import cn.information.bean.Product;
import cn.information.bean.Purchase;
import cn.information.dao.PurchaseDao;

import javax.swing.*;
import java.awt.*;
import java.util.List;

public class DateQueryUI extends JFrame {
    private JComboBox<String> dateComboBox;
    private JButton btnConfirm;
    private JButton btnCancel;

    public DateQueryUI()
    {
        setTitle("消费日期查询");
        setSize(400, 200);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        JPanel panelCenter = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 20));
        JPanel panelSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));

        PurchaseDao  purchaseDao = new PurchaseDao();
        List<Purchase>purchases = purchaseDao.findAll();
        String[] dates = purchases.stream()
                .map(Purchase::getDate)
                .distinct()
                .toArray(String[]::new);


        panelCenter.add(new JLabel("请选择查询时间:"));
        dateComboBox = new JComboBox<>(dates);
        panelCenter.add(dateComboBox);

        btnConfirm = new JButton("确认");
        btnConfirm.setEnabled(false); // Initially disabled
        panelSouth.add(btnConfirm);

        JButton btnCancel = new JButton("取消");
        btnCancel.addActionListener(e -> dispose());
        panelSouth.add(btnCancel);

        add(panelCenter, BorderLayout.CENTER);
        add(panelSouth, BorderLayout.SOUTH);

        // Add listener to combo box
        dateComboBox.addActionListener(e -> {
            if (dateComboBox.getSelectedIndex() >= 0) {
                btnConfirm.setEnabled(true);
            } else {
                btnConfirm.setEnabled(false);
            }
        });

        // Add listener to confirm button
        btnConfirm.addActionListener(e -> {
            String selectedDate = (String) dateComboBox.getSelectedItem();
            new DateQueryResultUI(selectedDate).setVisible(true);
            dispose();
        });

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

}


